// 1.插件挂载$store
// 2.实现store

let Vue;
class Store {
  constructor(options) {
    // data响应式
    // this.state = new Vue({
    //   data: options.state,
    // })
    
    // console.log(this.state.counter);
    this._wrappedGetters = options.getters
    this._mutations = options.mutations;
    this._actions = options.actions;
    
    this.getters = {};
    const computed = {};
    const store = this;
    // 将传入的getters添加到store的getters上
    Object.keys(this._wrappedGetters).forEach(key => {
      console.log(key);
      const fn = this._wrappedGetters[key]
      computed[key] = function() {
        return fn(store.state);
      };
      Object.defineProperty(store.getters, key, {
        get: () => store._vm[key]
      })
    })
    this._vm = new Vue({
      data: {
        $$state: options.state
      },
      computed
    });
    this.commit = this.commit.bind(this);
    this.dispatch = this.dispatch.bind(this);

  }
  get state() {
    console.log("_vm", this._vm);
    return this._vm._data.$$state;
  }

  set state(v) {
    console.error("不可以这样修改");
  }

  commit(type, payload) {
    const entry = this._mutations[type];
    if (!entry) {
      console.error('unKown mutation');
    }
    entry(this.state, payload);
  }
  dispatch(type, payload) {
    const entry = this._actions[type];
    if (!entry) {
      console.error('unKown mutation');
    }
    entry(this, payload);
  }
}

function install(_vue) {
  Vue = _vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store;
      }
    }
  });
}

export default {
  Store,
  install
};